<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2022/1/7
 * Time: 15:03
 */

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\Active;
use app\common\model\Circle;
use app\common\model\Clock;
use app\common\model\Config;
use app\common\model\District;
use app\common\model\Industry;
use app\common\model\Shop as ModelShop;
use app\common\model\ShopAudit;
use app\common\model\User;
use app\common\validate\Shop as ValidateShop;
use think\Db;
use think\Exception;

/**
 * 店铺接口
 * Class Shop
 * @package app\api\controller
 */
class Shop extends Api
{
    protected $noNeedLogin = ['get_list', 'get_info', 'shop_clock_rank', 'active_list', 'get_service_time'];
    protected $noNeedRight = ['*'];

    /**
     * 回显商家认证
     */
    public function audit_show(){
        $user_id = $this->auth->id;
        $audit = ShopAudit::where(['user_id'=> $user_id])->order('id desc')->find();
        $data = [];
        if($audit){
            $data['id'] = $audit['id'];
            $data['industry_id'] = $audit['industry_id'];
            $data['industry_name'] = Industry::where('id', $audit['industry_id'])->value('name');
            $data['type'] = $audit['type'];
            $typeList = ShopAudit::getTypeArray();
            $data['type_name'] = $typeList[$audit['type']];
            $data['status'] = $audit['status'];
            if($audit['status'] == ShopAudit::STATUS_AUDIT_PASS && $audit['expiration_time'] <= time()){
                $data['status'] = ShopAudit::STATUS_AUDIT_EXPIRATION;
            }
            $data['remark'] = $audit['remark'];
            $data['phone_name'] = $audit['phone_name'];
            $data['phone'] = $audit['phone'];
        }
        $this->success("获取成功", $data);
    }
    /**
     * 商家认证  提交申请
     *
     */
    public function save_audit(){
        $type = $this->request->param('type', ShopAudit::TYPE_SHOP_ONE);
        $phone_name = $this->request->param('phone_name', '');
        $phone = $this->request->param('phone', '');
        $industry_id = $this->request->param('industry_id', '');
        $user_id = $this->auth->id;
//        if(ShopAudit::where(['user_id'=> $user_id, 'status'=>ShopAudit::STATUS_AUDIT_ING])->count()){
//            $this->error("已存在审核中的记录，不能添加审核");
//        }
//        if(ShopAudit::where(['user_id'=> $user_id, 'status'=>ShopAudit::STATUS_AUDIT_PASS, 'expiration_time' => ['>', time()]])->count()){
//            $this->error("已存在未过期审核记录，不能添加审核");
//        }
        $saveData = [];
        $audit = ShopAudit::where(['user_id'=> $user_id])->order('id desc')->find();

        if($audit){
            if($audit['status'] == ShopAudit::STATUS_AUDIT_PASS){
                if($audit['expiration_time'] <= time()){
//                    $saveData['apply_time'] = time();
//                    $saveData['status'] = ShopAudit::STATUS_AUDIT_ING;
//                    $saveData['remark'] = '';
//                    $audit->delete();
                }else{
                    $this->error("不可编辑");
                }
            }else if($audit['status'] == ShopAudit::STATUS_AUDIT_REFUSE){
//                $saveData['apply_time'] = time();
//                $saveData['status'] = ShopAudit::STATUS_AUDIT_ING;
//                $saveData['remark'] = '';
//                $audit->delete();
            }else{
                if(!in_array($type, [ShopAudit::TYPE_SHOP_ONE, ShopAudit::TYPE_SHOP_CHAIN])){
                    $this->error("参数错误");
                }
                if(empty($industry_id)){
                    $this->error("请选择行业");
                }
                if(empty($phone_name)){
                    $this->error("联系人不能为空");
                }
                if(empty($phone)){
                    $this->error("联系电话不能为空");
                }
                if($audit['industry_id'] != $industry_id){
                    $saveData['industry_id'] = $industry_id;
                }
                if($audit['phone_name'] != $phone_name){
                    $saveData['phone_name'] = $phone_name;
                }
                if($audit['phone'] != $phone){
                    $saveData['phone'] = $phone;
                }
                if($saveData){
                    $res = $audit->save($saveData);
                    if($res){
                        $this->success("成功");
                    }
                    $this->error("失败");
                }
                $this->error("记录未修改任何数据");
            }
        }

        if(!in_array($type, [ShopAudit::TYPE_SHOP_ONE, ShopAudit::TYPE_SHOP_CHAIN])){
            $this->error("参数错误");
        }
        if(empty($industry_id)){
            $this->error("请选择行业");
        }
        if(empty($phone_name)){
            $this->error("联系人不能为空");
        }
        if(empty($phone)){
            $this->error("联系电话不能为空");
        }
        $saveData['phone_name'] = $phone_name;
        $saveData['industry_id'] = $industry_id;
        $saveData['phone'] = $phone;
        $saveData['type'] = $type;
        $saveData['user_id'] = $user_id;
        $saveData['apply_time'] = time();

        Db::startTrans();
        try{
            //当为单店的时候 、、如果当前用户认证下面有多个店铺，把此用户下除最新的店铺外，全部下架
            if($saveData['type'] == ShopAudit::TYPE_SHOP_ONE){
                //判断该用户下有多少个店铺
                $count = ModelShop::where('user_id',$user_id)->where('is_show',ModelShop::IS_SHOW_YES)->count();
                if($count > 1){
                    $id = ModelShop::where('user_id',$user_id)->order('id','desc')->find();
                    ModelShop::where('user_id',$user_id)->where('id','<',$id['id'])->update(['is_show'=>ModelShop::IS_SHOW_NOT]);
                }
            }
            ShopAudit::create($saveData);
            Db::commit();
        }catch (Exception $e){
            Db::rollback();
            $this->error("申请失败");
        }
        $this->success("申请成功");
    }

    /**
     * 特惠活动列表
     */
    public function active_list(){
        $list = Active::where('status', Active::STATUS_UP)->field('id,shop_id,title,image,describe,discount')->paginate($this->pagenum);
        foreach($list as &$item){
            $item['image'] = getRealImg($item['image']);
        }
        $this->success("获取成功", $list);
    }

    /**
     * 店铺列表
     */
    public function get_list(){
        $params = $this->request->param();
        $params['province_id'] = 27833;
        $params['city_id'] = 28141;
        $params['is_show'] = ModelShop::IS_SHOW_YES;
        // 2022-05-09 取消附近范围限制
        if(!isset($params['map_m']) || empty($params['map_m'])){
            // $params['map_m'] = 30 * 1000; // 30KM内店铺
        }
        $fields = ['shop.id,shop.name,shop.logo,shop.flag,shop.vip_tage,shop.avg_price,shop.city_id,shop.circle_id,shop.province_id,shop.lat,shop.lng,shop.address,shop.area_id,shop.street_id,audit.phone_name,audit.phone,audit.type as shop_type, user.nickname as user_name, shop.user_id, user.area_id as store_area_id,shop.is_top,audit.industry_id'];
        $order = 'shop.weigh desc,shop.id desc';
        $params['top'] = 1;
        if($this->auth->isLogin()){
            $params['self'] = $this->auth->id;
        }
        $list = ModelShop::getListPage($params, $fields, $order);

        $this->success("OK", $list);
    }
    /**
     * 店铺详情
     */
    public function get_info(){
        $id = $this->request->param('id');
        $lat = $this->request->param('lat', '');
        $lng = $this->request->param('lng', '');
        $fields = ['shop.id,shop.name,shop.logo,shop.images,shop.flag,shop.is_show,shop.business,user.status as user_status,shop.introduce,shop.circle_id,shop.province_id,shop.vip_tage,shop.image,shop.avg_price,shop.user_id,user.area_id as store_area_id,shop.street_id,shop.city_id,shop.address,shop.is_show,shop.phone as shop_phone,shop.lat,shop.lng,user.store_id,user.nickname as user_name, user.industry, shop.area_id'];
        if($lat && $lng){
            $fields[] = 'ROUND(' . ModelShop::EARTH_RADIUS . ' * 2 * ASIN(SQRT(POW(SIN((' . $lat . ' * PI() / 180 - shop.lat * PI() / 180) / 2), 2) + COS(' . $lat . ' * PI() / 180) * COS(shop.lat * PI() / 180) * POW(SIN((' . $lng . ' * PI() / 180 - shop.lng * PI() / 180) / 2), 2))) * 1000) AS juli';
        }
        $row = model('Shop')->getInfo($id, $fields, $this->auth->id);
        if(!$row){
            $this->error(model('Shop')->getError());
        }
        $this->success("获取成功", $row);
    }

    /**
     * 我的店铺
     */
    public function my_shop_list(){
        $user_id = $this->auth->id;
        $status = $this->auth->status;
        $audit = ShopAudit::where(['user_id'=> $user_id])->order('id desc')->find();
        if(!$audit){
            $this->error("没权限，请先申请认证店家");
        }else{
            $data['is_audit'] = $audit['status'];
//            if($audit['status'] != ShopAudit::STATUS_AUDIT_PASS){
//                $this->error("店家认证未通过");
//            }
            if($audit['status'] == ShopAudit::STATUS_AUDIT_PASS && $audit['expiration_time'] <= time()){
                $data['is_audit'] = ShopAudit::STATUS_AUDIT_EXPIRATION;
//                $this->error("店家认证已过期，请重新申请");
            }
        }
        if ($status != 'normal') {
            $data['is_audit'] = ShopAudit::STATUS_AUDIT_HIDDEN;
        }
        $params['user_id'] = $user_id;
        $params['my'] = $user_id;
        $params['self'] = $user_id;
        $fields = ['shop.id,shop.name,shop.circle_id,shop.logo,shop.flag,shop.is_show,shop.vip_tage,shop.avg_price,shop.city_id,shop.province_id,shop.area_id,shop.user_id,shop.street_id,audit.type as shop_type, user.area_id as store_area_id, audit.industry_id'];
        $order = 'shop.is_show desc,shop.weigh desc,shop.id desc';

        $list = ModelShop::getListPage($params, $fields, $order);

        $data['start_time'] = $audit ? date("Y-m-d", $audit['audit_time']) : '';
        $data['end_time'] = $audit ? date("Y-m-d", $audit['expiration_time']) : '';
        $data['list'] = $list;
        $this->success("OK", $data);
    }

    /**
     * 添加店铺
     */
    public function save_shop(){
        $this->request->filter('trim');
        $user_id = $this->auth->id;
        $status = $this->auth->status;
        $audit = ShopAudit::where(['user_id'=> $user_id])->order('id desc')->find();
        if(!$audit){
            $this->error("未认证店家，请先认证");
        }else{
            if($audit['status'] == ShopAudit::STATUS_AUDIT_ING){
                $this->error("认证店家中，暂不能添加店铺");
            }
            if($audit['status'] == ShopAudit::STATUS_AUDIT_REFUSE){
                $this->error("店家认证未通过，请重新认证");
            }
            if($audit['status'] == ShopAudit::STATUS_AUDIT_PASS){
                if($audit['expiration_time'] <= time()){
                    $this->error("店家认证已过期，请重新认证");
                }
            }
        }
        if ($status != 'normal') {
            $this->error("店家认证已禁用，请联系管理员");
        }

        $params = $this->request->param();
        // 单店只能发布一个店铺
        if($audit['type'] == ShopAudit::TYPE_SHOP_ONE){
            if(isset($params['id']) && $params['id']){
                if($params['is_show'] == ModelShop::IS_SHOW_YES && ModelShop::get(['id'=>['neq', $params['id']], 'is_show'=> ModelShop::IS_SHOW_YES, 'user_id' => $user_id])){
                    $this->error("已有店铺上架");
                }
            }else{
                if(ModelShop::get(['user_id'=>$user_id])){
                    $this->error("不能添加多个店铺");
                }
            }
        }

        $params['province_id'] = 27833;
        $params['city_id'] = 28141;

        if(!isset($params['name']) || empty($params['name'])){
            $this->error("店铺名称不能为空");
        }
        if(!isset($params['logo']) || empty($params['logo'])){
            $this->error("店铺图片不能为空");
        }
        if(!isset($params['image']) || empty($params['image'])){
            $this->error("店铺分享图片不能为空");
        }
        if(!isset($params['area_id']) || empty($params['area_id']) || !isset($params['street_id'])|| empty($params['street_id'])){
            $this->error("请选择省市区街道");
        }
        if(!isset($params['circle_id']) || empty($params['circle_id'])){
            $this->error("请选择商圈");
        }
        if(!isset($params['lng']) || empty($params['lng']) || !isset($params['lat']) || empty($params['lat'])){
            $this->error("请定位店铺位置");
        }
        if(!isset($params['address']) || empty($params['address'])){
            $this->error("请输入店铺地址");
        }
        if(!isset($params['phone']) || empty($params['phone'])){
            $this->error("请输入联系电话");
        }
        if(!isset($params['business']) || empty($params['business'])){
            $this->error("请输入店铺营业时间");
        }
        if(!isset($params['introduce']) || empty($params['introduce'])){
            $this->error("请输入店铺介绍");
        }
        if(!isset($params['vip_tage']) || empty($params['vip_tage'])){
            $this->error("请输入会员折扣");
        }
        if($params['vip_tage'] > 100){
            $this->error("会员折扣不能超过100%");
        }
        if(!isset($params['avg_price']) || empty($params['avg_price'])){
            $this->error("请输入人均消费");
        }
//        if(!isset($params['is_show']) || !in_array($params['is_show'], ['0','1'])){
//            $this->error("请选择是否显示");
//        }
        if(!isset($params['is_show']) && !in_array($params['is_show'], ['0','1'])){
            $this->error("参数错误");
        }
        if(isset($params['id']) && $params['id']){
            $row = ModelShop::get($params['id']);
            if(!$row){
                $this->error("店铺参数错误");
            }
            if($row['user_id'] != $user_id){
                $this->error("不是自己的店铺，不能修改!");
            }
            $res = $row->allowField(true)->isUpdate(true)->save($params);
            /*if($res){
                if($params['is_show'] == ModelShop::IS_SHOW_YES){
                    ModelShop::where('user_id',$user_id)->where('id','<>',$params['id'])->update(['is_show'=>ModelShop::IS_SH0OW_NOT]);
                }
            }*/
            $text = "编辑";
        }else{
            $params['user_id'] = $user_id;
            $res = model('Shop')->allowField(true)->save($params);
            $text = "添加";
        }

        if($res){
            $this->success($text.'成功');
        }else{
            $this->error($text.'失败');
        }
    }

    /**
     * 删除店铺
     */
    public function del_shop(){
        $shop_id = $this->request->param('shop_id');
        $user_id = $this->auth->id;
        $shop = ModelShop::get($shop_id);
        if(!$shop){
            $this->error("店铺信息错误");
        }
        if($shop['user_id'] != $user_id){
            $this->error("不是自己的店铺，不能删除!");
        }
        $res = ModelShop::where('id', $shop_id)->delete();
        if($res){
            $this->success("删除成功");
        }
        $this->error("删除失败");
    }

    /**
     * 上下架店铺
     */
    public function up_down_shop(){
        $shop_id = $this->request->param('shop_id');
        $is_show = $this->request->param('is_show');
        if(empty($shop_id)){
            $this->error("参数错误");
        }
        if(!isset($is_show) && !in_array($is_show, ['0','1'])){
            $this->error("店铺状态参数错误");
        }
        $user_id = $this->auth->id;
        $shop = ModelShop::get($shop_id);
        if(!$shop){
            $this->error("店铺信息错误");
        }
        if($shop['user_id'] != $user_id){
            $this->error("不是自己的店铺，不能修改!");
        }

        if($is_show == ModelShop::IS_SHOW_YES){
            $text = "上架";
        }else{
            $text = "下架";
        }
        if($shop->is_show == $is_show){
            $this->error("店铺已" . $text . "!");
        }

        $res = $shop->save(['is_show' => $is_show]);
        if($res){
            $this->success($text . "成功！");
        }
        $this->error($text . "失败！");
    }

    /**
     * 打卡
     */
    public function shop_clock(){
        $shop_id = $this->request->param('shop_id');
        $user_id = $this->auth->id;
        $shop = ModelShop::get($shop_id);
        if(!$shop){
            $this->error("店铺信息错误");
        }
        $audit = ShopAudit::where(['user_id'=> $shop['user_id']])->order('id desc')->find();
        if(!$audit){
            $this->error("店铺信息错误");
        }else{
            if($audit['status'] != ShopAudit::STATUS_AUDIT_PASS){
                $this->error("店铺已关闭");
            }
            if($audit['expiration_time'] <= time()){
                $this->error("店铺已关闭");
            }
        }
        $saveData = ['shop_id'=> $shop_id, 'user_id' => $user_id];
        if($shop['user_id'] == $user_id){
            $this->error("不能给自己的店铺打卡!");
        }
        $min_time = strtotime(date("Y-m-d"));
        $max_time = $min_time + 86400 - 1;
        if(Clock::where($saveData)->where('createtime', 'BETWEEN', [$min_time, $max_time])->count()){
            $this->error("今天已在该店铺打卡!");
        }
        Db::startTrans();
        try{
            Clock::create($saveData);
            $shop->save(['clock_number' => $shop['clock_number'] + 1]);
            Db::commit();
        }catch(Exception $e){
            Db::rollback();
            $this->error("打卡失败");
        }
        $this->success("打卡成功");
    }

    /**
     * 打卡足迹
     */
    public function clock_shop_list(){
        $user_id = $this->auth->id;
        $keywords = $this->request->param('keywords', '');
        $where = ['c.user_id' => $user_id];
        if($keywords){
            $where['shop.name'] = ['like', "%$keywords%"];
        }
        $fields = ['shop.id,shop.name,shop.logo,shop.flag,shop.vip_tage,shop.avg_price,shop.area_id,shop.street_id,c.createtime'];
        $data = Clock::alias('c')
            ->join('Shop shop', 'c.shop_id = shop.id')
            ->whereNull('shop.delete_time')
            ->where($where)
            ->field($fields)
            ->order('c.createtime desc')
            ->paginate($this->pagenum);
        foreach($data as &$item){
            $item['createtime_text'] = date('Y-m-d', $item['createtime']);
//            $flag = model('ShopFlag')->where('id', 'in', $item['flag'])->order('weigh desc,id desc')->column('name');
            $item['flag'] = explode(",", $item['flag']);
            $item['logo'] = getRealImg($item['logo']);
            $item['area_name'] = District::where('id', $item['area_id'])->value('name') ?: '';
            $item['street_name'] = District::where('id', $item['street_id'])->value('name') ?: '';
            $item['vip_tage'] = number_format($item['vip_tage']/10, 2, '.', '') - 0;

            unset($item['area_id']);
            unset($item['street_id']);
            unset($item['industry_id']);
        }
        $this->success("获取成功", $data);
    }

    /**
     * 获取服务器时间戳
     */
    public function get_service_time(){
        $this->success("获取成功", time());
    }
    /**
     * 店铺打卡排行榜
     */
    public function shop_clock_rank(){
        $fields = ['shop.id,shop.name,shop.logo,shop.flag,shop.vip_tage,shop.avg_price,count(c.id) as clock_number,shop.city_id,shop.circle_id,shop.province_id,shop.area_id,shop.user_id,shop.street_id,audit.type as shop_type,max(c.createtime) as max_time,audit.industry_id'];
        // 获取排行榜开始结束时间
        $start_time = Config::getConfigValue('clock_start_time');
        $end_time = Config::getConfigValue('clock_end_time');
        $time = $this->request->param('time', '');
        if(empty($time)){
            $time = strtotime(date('Y-m-d'));
        }
        if($start_time){
            $start_time = strtotime($start_time);
        }
        if($end_time){
            $end_time = strtotime($end_time." 23:59:59");
        }
        $rank_time_where = false;
        if($start_time && $end_time){
            if($end_time > $time){
                $end_time = $time;
            }
            $rank_time_where = true;
        }elseif($start_time && empty($end_time)){
            $end_time = $time;
            $rank_time_where = true;
        }elseif(empty($start_time) && $end_time){
            if($end_time > $time){
                $end_time = $time;
            }
            $rank_time_where = true;
        }

        $model = ModelShop::alias('shop')
            ->join('User user', 'shop.user_id = user.id')
            ->join('UserShopAudit audit', 'user.id = audit.user_id');
        if($rank_time_where){
            if($start_time && $end_time){
                $model->join('Clock c', 'shop.id = c.shop_id and c.createtime BETWEEN '.$start_time.' and '.$end_time, 'left');
            }elseif($start_time && empty($end_time)){
                $model->join('Clock c', 'shop.id = c.shop_id and c.createtime >= '.$start_time, 'left');
            }elseif(empty($start_time) && $end_time){
                $model->join('Clock c', 'shop.id = c.shop_id and c.createtime <= '.$end_time, 'left');
            }
        }else{
            $model->join('Clock c', 'shop.id = c.shop_id and c.createtime < '. $time, 'left');
        }
        $list = $model->whereNull('audit.delete_time')
            ->whereNull('shop.delete_time')
            ->where('shop.is_show', ModelShop::IS_SHOW_YES)
            ->where('user.status', 'normal')
            ->where('audit.status', ShopAudit::STATUS_AUDIT_PASS)
            ->where('audit.expiration_time', '>', time())
            ->field($fields)
            ->order('clock_number desc,max_time asc,shop.createtime asc')
            ->group('shop.id')
            ->paginate($this->pagenum);

        $typeArray = ShopAudit::getTypeArray();

        $self_id = 0;
        if($this->auth->isLogin()){
            $self_id = $this->auth->id;
        }

        foreach ($list as $key => &$value) {
            $value['logo'] = getRealImg($value['logo']);
            $value['flag'] = explode(",", $value['flag']);
            $value['user_name'] = '';
            $value['shop_type_name'] = '';
            $value['is_self'] = 0;
            if($value['user_id'] && $self_id){
                if($value['user_id'] == $self_id){
                    $value['is_self'] = 1;
                }
            }
            $value['province_name'] = District::where('id', $value['province_id'])->value('name') ?: '';
            $value['city_name'] = District::where('id', $value['city_id'])->value('name') ?: '';
            $value['area_name'] = District::where('id', $value['area_id'])->value('name') ?: '';
            $value['street_name'] = District::where('id', $value['street_id'])->value('name') ?: '';
            $value['industry_name'] = Industry::where('id', $value['industry_id'])->value('name') ?: '';
            $value['circle_name'] = Circle::where('id', $value['circle_id'])->value('name') ?: '';
            $value['shop_type_name'] = $typeArray[$value['shop_type']];
            // 排行
            $value['rank'] = 0;
            if($value['clock_number']){
                $rankModel = Clock::alias('c')->join('Shop s', 'c.shop_id = s.id')->whereNull('s.delete_time');
                $count1Model = Clock::alias('c')->join('Shop s', 'c.shop_id = s.id')->whereNull('s.delete_time');
                if($rank_time_where){
                    if($start_time && $end_time){
                        $rankModel->whereBetween('c.createtime', [$start_time, $end_time]);
                        $count1Model->whereBetween('c.createtime', [$start_time, $end_time]);
                    }elseif($start_time && empty($end_time)){
                        $rankModel->where('c.createtime >= '.$start_time);
                        $count1Model->where('c.createtime >= '.$start_time);
                    }elseif(empty($start_time) && $end_time){
                        $rankModel->where('c.createtime <= '.$end_time);
                        $count1Model->where('c.createtime <= '.$end_time);
                    }
                }else{
                    $rankModel->where('c.createtime < '. $time);
                    $count1Model->where('c.createtime < '. $time);
                }
                $rank = $rankModel->group('c.shop_id')->having('count(*) > '.$value['clock_number'])->select();
                $count1 = $count1Model->where('c.createtime', '<', $value['max_time'])->group('c.shop_id')->having('count(*) = '.$value['clock_number'])->select();
                $value['rank'] = count($rank) + count($count1) + 1;
            }
            $value['vip_tage'] = number_format($value['vip_tage']/10, 2, '.', '') - 0;


            unset($value['type']);
            unset($value['province_id']);
            unset($value['city_id']);
            unset($value['area_id']);
            unset($value['street_id']);
            unset($value['createtime']);
            unset($value['delete_time']);
            unset($value['store_id']);
            unset($value['circle_id']);
            unset($value['industry_id']);
            unset($value['weigh']);
            unset($value['is_show']);
            unset($value['user_id']);
        }

        $this->success("获取成功", $list);
    }

}